<template>
  <div class="pagestyle">
    <list_controller ref="zujianname" :options="state.options" :noprintDownShow="true">
      <template v-slot:opraCurdBtnlist="row">
        <span>
          <el-button class="tableFontSize" type="primary" link size="small" @click="editBtn(row.row.row)">编辑
          </el-button>
          <el-button class="tableFontSize" type="primary" link size="small" @click="deleteBtn(row.row.row)">删除
          </el-button>
        </span>
      </template>
      <template v-slot:opraCurdBtnAll>
        <span :class="state.addModal ? 'listInfoBtn active' : 'listInfoBtn'" @click="addBtn('mul')">
          <svg-icon :class="state.addModal ? 'active' : ''" class-name="search-icon" icon-class="xinzeng" />
          新增
        </span>
        <span :class="'listInfoBtn'" @click="deleteBtn('mul')">
          <svg-icon class-name="search-icon" icon-class="shanchu" />
          删除
        </span>
        <oneclickDelivery style="margin:0 0 0 12px;"></oneclickDelivery>
      </template>
      <template v-slot:selectNamelist> 标校管理 </template>
      <template v-slot:listSS="{ row, field }">
        <span v-if="field == 'measureRank'">
          <svg-icon v-for="item in row.measureRank" class-name="search-icon" icon-class="xingactive" />
          <span v-if="row.measureRank < 3">
            <svg-icon v-for="item in 3 - row.measureRank" class-name="search-icon" icon-class="xing" />
          </span>
        </span>
        <span v-if="field == 'preset'">
          <span v-if="row.preset">是</span>
          <span v-else>否</span>
        </span>
      </template>
    </list_controller>
    <!-- 新增弹框 -->
    <!-- <teleport to="body"> -->
      <vxe-modal esc-closable destroy-on-close :lock-view="false" :width="1000" :height="auto" v-model="state.addModal"
        resize :mask="true" showFooter>
        <template #title>
          <div class="w100 h100 fsc mask_title">{{ state.modalTitle }}</div>
        </template>
        <template #default>
          <div class="form_box">
            <el-form ref="formRef" :model="state.formData" :rules="state.rules" label-position="top">
              <el-row :gutter="20">
                <el-col :span="24" v-if="state.modalTitle !='编辑标校管理'">
                  <div
                    style="display:flex;align-items:center;border-radius: 4px;padding:4px;color:rgba(255, 85, 85, 1);
background: linear-gradient(0deg, rgba(255, 85, 85, 0.12), rgba(255, 85, 85, 0.12)), rgba(255, 255, 255, 1);border:1px solid rgba(255, 85, 85, 0.12)">
                    <svg-icon class-name="search-icon" icon-class="tishi" />
                    <span>请选择需要添加的测点!</span>
                  </div>
                </el-col>
                <el-col :span="24">
                  <querybox :queryList="state.optionsTwo.queryList.querys" @query="queryClick"
                    v-if="state.modalTitle!='编辑标校管理'">
                  </querybox>
                  <vxe-table ref="tableTwo" height="200" :data="state.dataList" border="inner"
                    @checkbox-change="checkchange">
                    <vxe-column type="checkbox" v-if="state.modalTitle!='编辑标校管理'" :width="42"></vxe-column>
                    <vxe-column type="seq" :width="55" title="序号"></vxe-column>
                    <vxe-column v-for="(item, index) in state.optionsTwo.tableheads" :field="item.field"
                      :title="item.title" :params="{ name: item.name }" :width="item.width ? item.width : ''"
                      :key="index">
                    </vxe-column>
                  </vxe-table>
                </el-col>

                <el-col :span="6">
                  <el-form-item label="间隔时间(天)" prop="intervalTime">
                    <el-input v-model="state.formData.intervalTime" placeholder="请输入">
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item prop="gasSample" v-if="state.modalTitle!='编辑标校管理'">
                    <label slot="label">
                      <div style="display:flex;align-items: center;">
                        <span>气样浓度</span>
                        <el-popover placement="top" :width="400" trigger="hover">
                          <template #reference>
                            <svg-icon class-name="search-icon" icon-class="tishi" />
                          </template>
                          <span>请确保在填写" 气样浓度"、"波动范围"或"持续时间"中的任意一项后，其他两项也需一并填写!</span>
                        </el-popover>
                      </div>
                    </label>
                    <el-input v-model="state.formData.gasSample" oninput="value =value.replace(/[^\-\d.]/g, '') .replace(/^\./g, '').replace(/\.{2,}/g,
'.').replace(/(\.\d+)\./g, '$1') .replace(/(-)\./g, '$1') .replace(/\-{2,}/g, '-')
.replace(/(\d+|\.)-/g, '$1') .replace(/-(0){2,}/g,'$1') .replace(/(-)0+(\d+)/g, '$1$2')
.replace(/^0+(\d)/, '$1')  .replace(/(\.\d{2})\d*/, '$1')" placeholder="请输入">
                    </el-input>
                  </el-form-item>
                  <el-form-item v-if="state.modalTitle =='编辑标校管理'">
                    <template #label>
                      气样浓度({{state.unit}})
                    </template>
                    <el-input oninput="value =value.replace(/[^\-\d.]/g, '') .replace(/^\./g, '').replace(/\.{2,}/g,
'.').replace(/(\.\d+)\./g, '$1') .replace(/(-)\./g, '$1') .replace(/\-{2,}/g, '-')
.replace(/(\d+|\.)-/g, '$1') .replace(/-(0){2,}/g,'$1') .replace(/(-)0+(\d+)/g, '$1$2')
.replace(/^0+(\d)/, '$1')  .replace(/(\.\d{2})\d*/, '$1')" v-model="state.formData.gasSample" placeholder="请输入">
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="波动范围" prop="waveRange">
                    <el-input oninput="value =value.replace(/[^\-\d.]/g, '') .replace(/^\./g, '').replace(/\.{2,}/g,
'.').replace(/(\.\d+)\./g, '$1') .replace(/(-)\./g, '$1') .replace(/\-{2,}/g, '-')
.replace(/(\d+|\.)-/g, '$1') .replace(/-(0){2,}/g,'$1') .replace(/(-)0+(\d+)/g, '$1$2')
.replace(/^0+(\d)/, '$1')  .replace(/(\.\d{2})\d*/, '$1')" v-model="state.formData.waveRange" placeholder="请输入">
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="稳定时长(秒)" prop="duration">
                    <el-input oninput="value=value.replace(/[^0-9]/g,'')" v-model="state.formData.duration"
                      placeholder="请输入">
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </template>
        <template #footer>
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm"> 确定 </el-button>
        </template>
      </vxe-modal>
    <!-- </teleport> -->
  </div>
</template>
<script setup>
  import querybox from "@/components/commonCom/querybox";
  import oneclickDelivery from "@/components/commonCom/oneclickDelivery";
  import list_controller from "@/components/commonCom/list_controller";
  import {
    computed,
    onMounted,
    reactive
  } from "vue";
  import {
    ElMessage,
    ElMessageBox
  } from 'element-plus'
  import {
    table_headers
  } from "@/components/commonCom/table_headers";
  import axios from "@/utils/request";
  import usePagesStore from "@/store/modules/pages";
  import {
    getlistAlarmTypesList,
    getlistSimulatePoints,
    getlistSensorName,
    getlistSitesList,
  } from "@/api/config";
  const {
    proxy
  } = getCurrentInstance();
  const store = usePagesStore();
  const router = useRouter();
  let previewHttps =
    import.meta.env.VITE_APP_HTTP;
  components: {
    list_controller;
  }
  const upload = ref(null);
  let state = reactive({
    checkboxConfig: [],
    dataList: [],
    options: {
      tableheads: computed(() => table_headers.configCalibration),
      listSS: [{
          field: "preset",
        },
        {
          field: "measureRank",
        },
      ],
      queryList: {
        dropdownUrl: "",
        querys: [{
          field: "pointId",
          title: "分站",
          type: "select",
          binddata: "",
          options: [],
        }, ],
      },
      dataUrl: "/calibration/list",
      delUrl: "/calibration/del",
      addUrl: "/calibration/add",
      descUrl: "/calibration/getById",
      editUrl: "/calibration/modifyCalibration",
    },
    optionsTwo: {
      tableheads: computed(() => table_headers.CalibrationPoint),
      queryList: {
        dropdownUrl: "",
        querys: [{
            field: "condition",
            title: "搜索",
            type: "input",
            binddata: "",
          },
          {
            field: "sensorName",
            title: "设备名称",
            type: "cascader",
            binddata: "",
            options: [],
            cascader_props: {
              children: "children",
              value: "name",
              label: "name",
              emitPath: false,
            },
          },
        ],
      },
    },
    // 表单
    addModal: false,
    modalTitle: "新增标校管理",
    drawerShow: false,
    formRef: null,
    formData: {
      gasSample: '',
      waveRange: '',
      duration: ''
    },
    rules: {
      intervalTime: [{
        required: true,
        message: "请输入间隔天数",
        trigger: "blur",
      }],
      // duration: [{
      //   required: true,
      //   message: "请输入稳定时长",
      //   trigger: "blur",
      // }, ],
      // gasSample: [{
      //   required: true,
      //   message: "请输入气样浓度",
      //   trigger: "blur",
      // }, ],
      // waveRange: [{
      //   required: true,
      //   message: "请输入波动范围",
      //   trigger: "blur",
      // }, 
      // ],
    },
    editId: undefined,
    stationInNumList: [{
        code: 1,
        label: "一般",
      },
      {
        code: 2,
        label: "重要",
      },
      {
        code: 3,
        label: "非常重要",
      },
    ],
    presetList: [{
        code: true,
        label: "是",
      },
      {
        code: false,
        label: "否",
      },
    ],
    unit: undefined
  });
  // 新增按钮
  function addBtn(row) {
    state.modalTitle = "新增标校管理";
    state.addModal = true;
    state.formData = {
      gasSample: '',
      waveRange: '',
      duration: ''
    };
    state.editId = undefined;
    state.fileList = [];
    state.optionsTwo.queryList.querys.forEach(item => {
      item.binddata = ''
    })
    getlistSensorNameData({})
  }
  // 编辑按钮
  function editBtn(row) {
    state.modalTitle = "编辑标校管理";
    state.addModal = true;
    axios
      .post(state.options.descUrl, {
        id: row.id,
      })
      .then((res) => {
        if (res.code == 200) {
          state.formData = res.data;
          state.editId = res.data.id;
          state.dataList = res.data.gasFireDtoList
          state.unit = res.data.gasFireDtoList[0].unit
        }
      });
  }

  function deleteBtn(row) {
    let ids = [];
    if (row != "mul") {
      ids = [row.id];
    } else {
      if (store.records.length > 0) {
        ids = store.records.map((item) => {
          return item.id;
        });
      } else {
        proxy.$modal.msgSuccess("请先勾选所要删除数据!");
      }
    }
    if (ids.length > 0) {
      ElMessageBox.confirm(
          '确定要删除该数据吗?',
          '温馨提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
        .then(() => {
          axios.post(state.options.delUrl, ids).then(res => {
            if (res.code == 200) {
              proxy.$refs['zujianname'].getData()
              state.addModal = false
              ElMessage({
                type: 'success',
                message: res.msg,
              })
              store.records = []
            }
          })

        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '删除取消',
          })
        })
    }
  }
  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["formRef"].validate((valid) => {
      if (valid) {

        if (state.editId) {
          state.formData.id = state.editId;
          if ((state.formData.gasSample == null && state.formData.waveRange == null && state.formData.duration == null) ||
            (state.formData.gasSample != null && state.formData.waveRange != null && state.formData.duration != null)) {
            axios.post(state.options.editUrl, state.formData).then((res) => {
              if (res.code == 200) {
                proxy.$refs["zujianname"].getData();
                state.addModal = false;
                proxy.$modal.msgSuccess(res.msg);
              }
            });
          } else {
            proxy.$modal.msgWarning('气样浓度、波动范围、稳定时长三者都填或都不填');
          }

        } else {
          if ((state.formData.gasSample == '' && state.formData.waveRange == '' && state.formData.duration == '') ||
            (state.formData.gasSample != '' && state.formData.waveRange != '' && state.formData.duration != '')) {

            axios.post(state.options.addUrl, state.formData).then((res) => {
              if (res.code == 200) {
                proxy.$refs["zujianname"].getData();
                state.addModal = false;
                proxy.$modal.msgSuccess(res.msg);
              }
            });
          } else {
            proxy.$modal.msgWarning('气样浓度、波动范围、稳定时长三者都填或都不填');
          }
        }
      }
    });
  }

  function cancel() {
    state.addModal = false;
  }

  function getlistAlarmTypesData() {
    let arr = [];
    getlistSitesList().then((res) => {
      arr = Object.keys(res.data).map((item) => {
        return {
          label: item + "-" + res.data[item],
          value: item,
        };
      });
      state.options.queryList.querys[0].options = arr;
    });

    getlistSensorName({}).then((res) => {
      state.optionsTwo.queryList.querys[1].options = res.data;
    });
  }

  function getlistSensorNameData(data) {
    getlistSimulatePoints(data).then((res) => {
      state.dataList = res.data;
    });
  }

  function queryClick(type) {
    let data = {};
    if (type == 1) {
      state.optionsTwo.queryList.querys.forEach((item) => {
        data[item.field] = item.binddata;
      });
      getlistSensorNameData(data);
    } else if (type == 2) {
      state.optionsTwo.queryList.querys.forEach((item) => {
        data[item.field] = "";
      });
      getlistSensorNameData(data);
    }
  }

  function checkchange(e) {
    state.formData.gasFireDtoList = e.records;
  }
  getlistAlarmTypesData();
</script>
<style lang="scss" scoped>
:deep(.shouqiquery){
display: none;
}
  ::v-deep .el-drawer {
    .querycss {
      .fsc {
        &:nth-child(2) {
          display: none;
        }
      }
    }

    .table_box {
      .fsc {
        display: none;
      }
    }
  }
</style>